package dao

import (
	"activity_srv/model"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"log"
	"math/rand"
	model3 "order_srv/model"
	MQ "smart-health-platforms/inits"
	"smart-health-platforms/pkg"
	"time"
)

func GetBargain(BargainId int32, addressId int32, RealName string, UserPhone string, PayType string) (order model3.Order, err error) {
	var bargain model.BargainActivity
	bargain.Id = uint32(BargainId)
	err = bargain.GetBargainActivity()
	if err != nil {
		pkg.Error("查询失败")
		return
	}
	orderSn := "JD" + time.Now().Format("20060102150405") + fmt.Sprintf("%06d", rand.Intn(1_000_000))
	order = model3.Order{
		OrderSn:    orderSn,
		UserId:     uint32(bargain.UserId),
		GoodskuId:  bargain.SkrId,
		AddressId:  addressId,
		RealName:   RealName,
		UserPhone:  UserPhone,
		TotalNum:   1,
		TotalPrice: bargain.Price,
		PayStatus:  0,
		PayType:    PayType,
	}
	err = order.CreateBargainOrder()
	if err != nil {
		pkg.Error("失败", zap.Error(err))
		return
	}
	bargain.OrderSn = orderSn
	err = bargain.UpdateBargainActivity()
	if err != nil {
		pkg.Error("添加订单号", zap.Error(err))
		return model3.Order{}, err
	}
	rabbitmq := MQ.NewRabbitMQSimple("" +
		"2301a")

	// 发送消息
	marshal, _ := json.Marshal(order)
	msg, _ := rabbitmq.PublishSimple(marshal)
	log.Println("消息发送成功", msg)
	pkg.Info("订单创建成功", zap.Any("order", order))

	return order, nil
}
